package com.wcl.demo.ui.adapter;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.SpannableString;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageRequest;
import com.easemob.EMValueCallBack;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMConversation;
import com.easemob.chat.EMGroup;
import com.easemob.chat.EMGroupManager;
import com.easemob.chat.EMMessage;
import com.easemob.exceptions.EaseMobException;
import com.wcl.demo.R;
import com.wcl.demo.model.entity.SearchHimUser;
import com.wcl.demo.network.VolleySingleton;
import com.wcl.demo.ui.activity.ChatActivity;
import com.wcl.demo.utils.ActivityUtils;
import com.wcl.demo.utils.FaceConversionUtil;
import com.wcl.demo.utils.ParseManager;
import com.wcl.demo.utils.PreferenceManager;
import com.wcl.demo.utils.TimeStampUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by dllo on 15/11/26.
 */
public class NewsAdapter extends BaseAdapter {
    private List<EMConversation> datas;//定义会话信息
    private Context context;//定义context
    private VolleySingleton volleySingleton = VolleySingleton.getInstance();//定义Volley请求
    private List<String> usernames;

    //构造方法
    public NewsAdapter(Context context) {
        this.context = context;
    }

    //添加数据
    public void addData(List<EMConversation> datas) {
        this.datas = datas;
        notifyDataSetChanged();//当数据有改变的时候通知数据刷新
    }

    @Override
    public int getCount() {
        return datas != null && datas.size() > 0 ? datas.size() : 0;
    }

    @Override
    public Object getItem(int position) {
        return datas != null && datas.size() > 0 ? datas.get(position) : null;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, final ViewGroup parent) {
        if (datas != null && datas.size() > 0) {
            final ViewHolder holder;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.news_item, null);
                holder.news_head = (ImageView) convertView.findViewById(R.id.news_head);
                holder.news_contant = (TextView) convertView.findViewById(R.id.news_contant);
                holder.news_contexts = (TextView) convertView.findViewById(R.id.news_contexts);
                holder.news_time = (TextView) convertView.findViewById(R.id.news_time);
                holder.news_layout = (LinearLayout) convertView.findViewById(R.id.news_layout);
//                holder.news_user_head = (ImageView) convertView.findViewById(R.id.news_user_head);

                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            final EMConversation conversation = datas.get(position);
            final EMMessage lastMessage = conversation.getLastMessage();


            if (conversation.getIsGroup()) {
                Log.i("lanou66", "群聊传id");
                for (EMGroup emGroup : EMGroupManager.getInstance().getAllGroups()) {
                    if (emGroup.getGroupId().equals(conversation.getUserName())) {
                        holder.news_contant.setText(emGroup.getGroupName());
                    }
                }
            } else {
                holder.news_contant.setText(conversation.getUserName());
                try {
                    usernames = EMChatManager.getInstance().getContactUserNames();
                } catch (EaseMobException e) {
                    e.printStackTrace();
                }
                //设置用户头像
                ParseManager.getInstance().getContactInfos(usernames, new EMValueCallBack<List<SearchHimUser>>() {
                    @Override
                    public void onSuccess(List<SearchHimUser> searchHimUsers) {
                        for (int i = 0; i < searchHimUsers.size(); i++) {
                            SearchHimUser searchHimUser = searchHimUsers.get(i);
                            String HeadImageUrl = searchHimUser.getAvatar();
//                            Log.i("ACCESS_WIFI_STATE" , HeadImageUrl);
                            if (searchHimUsers != null && searchHimUsers.size() > 0) {
                                getBitmap(HeadImageUrl, holder.news_user_head);
                            }
                        }
                    }

                    @Override
                    public void onError(int i, String s) {

                    }
                });

            }

            if (datas != null && datas.size() > 0) {
                String[] str = (lastMessage.getBody() + "").split(":");
                if (str[0].equals("voice")) {
                    holder.news_contexts.setText("语音消息..");
                } else if (str[0].equals("image")) {
                    holder.news_contexts.setText("图片消息..");
                } else {
                    SpannableString spannableString = FaceConversionUtil.getInstace().getExpressionString(context, (lastMessage.getBody() + "").replace("txt:", "").replace("\"", ""));
                    holder.news_contexts.setText(spannableString);
                }
                long time = lastMessage.getMsgTime() / 1000 - TimeStampUtils.getTimesmorning();
                Log.i("lanou", "------------>" + time + "   " + TimeStampUtils.getTimesmorning());
                if ((time > 0 || time == 0) && time < 86400) {
                    holder.news_time.setText("今天" + TimeStampUtils.stampToDate2(lastMessage.getMsgTime()));
                } else if (time < 0 && ((time + 86400) > 0 || (time + 86400) == 0)) {
                    holder.news_time.setText("昨天" + TimeStampUtils.stampToDate2(lastMessage.getMsgTime()));
                } else {
                    holder.news_time.setText(TimeStampUtils.stampToDate(lastMessage.getMsgTime()));
                }

                holder.news_layout.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Bundle bundle = new Bundle();
                        if (conversation.getIsGroup()) {
                            Log.i("lanou66", "群聊传id");
                            for (EMGroup emGroup : EMGroupManager.getInstance().getAllGroups()) {
                                if (emGroup.getGroupId().equals(conversation.getUserName())) {
                                    bundle.putString("title", emGroup.getGroupName());
                                    bundle.putString("username", emGroup.getGroupId());
                                    bundle.putBoolean("groupchat", true);
                                    bundle.putString("oneself", lastMessage.getUserName());
                                }
                            }
                            //设置用户头像
                            ParseManager.getInstance().getContactInfos(usernames, new EMValueCallBack<List<SearchHimUser>>() {
                                @Override
                                public void onSuccess(List<SearchHimUser> searchHimUsers) {
                                    for (int i = 0; i < searchHimUsers.size(); i++) {
                                        SearchHimUser searchHimUser = searchHimUsers.get(i);
                                        String HeadImageUrl = searchHimUser.getAvatar();
                                        //getBitmap(HeadImageUrl, holder.news_user_head);
                                        Bundle bundle = new Bundle();
                                        bundle.putString("searchhimuser", HeadImageUrl);
//                                    Log.i("headimageurl" , HeadImageUrl);
                                    }
                                }

                                @Override
                                public void onError(int i, String s) {

                                }
                            });

                            //bundle.putString("username",emGroup.getGroupName());
                            ActivityUtils.startToActivity(parent.getContext(), ChatActivity.class, bundle);
                        } else {
                            bundle.putString("username", lastMessage.getUserName());
                        }
                        //bundle.putString("username",emGroup.getGroupName());
                        ActivityUtils.startToActivity(parent.getContext(), ChatActivity.class, bundle);
                    }
                });
                return convertView;
            }
        }
        return null;
    }

    public class ViewHolder {
        private ImageView news_head, news_user_head;
        private TextView news_contant, news_contexts, news_time;
        private LinearLayout news_layout;
    }

    /****
     * 从缓存中获取用户昵称
     *
     * @return
     */
    private String getCurrentUserNick() {
        return PreferenceManager.getInstance().getCurrentUserNick();
    }

    /***
     * 从缓存中获取用户头像
     *
     * @return
     */
    private String getCurrentUserAvatar() {
        return PreferenceManager.getInstance().getCurrentUserAvatar();
    }


    /***
     * 图片请求
     *
     * @param bitmap
     * @param imageView
     */
    private void getBitmap(String bitmap, final ImageView imageView) {
        ImageRequest request = new ImageRequest(bitmap, new Response.Listener<Bitmap>() {
            @Override
            public void onResponse(Bitmap response) {
                if (response != null) {
                    imageView.setImageBitmap(response);
                }
            }
        }, 50, 50, Bitmap.Config.ALPHA_8, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        });

//        volleySingleton.getImageResuest(bitmap, new Response.Listener<Bitmap>() {
//            @Override
//            public void onResponse(Bitmap response) {
//                if (response != null) {
//                    imageView.setImageBitmap(response);
//                }
//            }
//        });
    }

    private ImageView news_head;
    private TextView news_contant, news_contexts, news_time;
    private LinearLayout news_layout;
}
